<template>
  <div>
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左侧菜单栏 -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-position="'top'">
        <el-tabs
          tab-position="left"
          style="height: 600px"
          v-model="activeIndex"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="ruleForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="ruleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="ruleForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_number">
              <el-cascader
                v-model="ruleForm.goods_cat"
                :options="cateList"
                :props="cateProp"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的Item项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor
              ref="myTextEditor"
              v-model="content"
              :options="editorOption"
              style="height: 300px"
            ></quill-editor>
            <el-button type="primary" @click="addShop" class="addBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { number } from "echarts";
import { quillEditor } from "vue-quill-editor";
import addAPI from '../../api/add'
export default {
  components: {
    quillEditor,
  },
  name: "",
  data() {
    return {
      activeIndex: "0",
      //富文本
      content: "",
      editorOption: {
        placeholder: "编辑文章内容",
      },
      //添加商品
      ruleForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [], // 级联列表数据
      },
      rules: {
        goods_name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        goods_price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        goods_weight: [{ required: true, message: "请输入重量", trigger: "blur" }],
        goods_number: [{ required: true, message: "请输入数量", trigger: "blur" }],
      },
      //级联
      cateProp: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
      cateList: [], //商品分类列表
      // 静态属性
      onlyTableData: [],
      // 动态参数
      manyTableData: [],
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    //获取商品分类数据
    async getData() {
      const res = await addAPI.getData();
      //   console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error("获取商品分类数据失败");
      }
      this.cateList = res.data;
      //console.log(this.cateList);
    },

    //级联选择器触发，不是三级清空
    handleChange() {
      //console.log(this.ruleForm.goods_cat.length);
      if (this.ruleForm.goods_cat.length !== 3) {
        this.ruleForm.goods_cat = [];
      }
    },

    async tabClick() {
      // console.log(this.activeIndex)
      // 访问动态面板
      if (this.activeIndex === "1" && this.manyTableData.length === 0) {
        const res = await addAPI.tabClick(
          this.ruleForm.goods_cat[2],
          {
            params: { sel: "many" },
          }
        );
        console.log(res);

        // if (res.meta.status !== 200) {
        //   return this.$message.error("获取动态参数列表失败！");
        // }
        //  console.log(res.data)
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals.split(",");
        });
        this.manyTableData = res.data;
        console.log(this.manyTableData);
      }
      //访问静态面板
      if (this.activeIndex === "2" && this.oblyTableData.length === 0) {
        const { data: res } = await addAPI.tabClick(
          this.ruleForm.goods_cat[2],
          {
            params: { sel: "only" },
          }
        );

        // if (res.meta.status !== 200) {
        //   return this.$message.error("获取静态属性失败！");
        // }

        console.log(res.data);
        this.onlyTableData = res.data;
      }
    },
    //上传图片
    handleRemove(file) {
      console.log(file);
    },
    handlePreview(file) {
      console.log(file);
    },

    //确认添加商品
    addShop() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写必填的选项");
        }
        // console.log(this.ruleForm);
        let arr = this.deepClone(this.ruleForm);
        arr.goods_cat = arr.goods_cat.join(",");
        arr.attrs = [];
        this.manyTableData.forEach((item) => {
          arr.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          });
        });
        this.onlyTableData.forEach((item) => {
          arr.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          });
        });
        // console.log(arr);
        const res = await addAPI.addShop(arr);
        // console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("添加商品成功");
        this.$router.push("/goods");
      });
    },

    //深拷贝
    deepclone(obj) {
      if (typeof obj !== "object" || obj == null) {
        return obj;
      }
      let arr;
      if (obj instanceof Array) {
        arr = [];
      } else {
        arr = {};
      }
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          arr[key] = this.deepclone(obj[key]);
        }
      }
    },

    //富文本编辑器
    onEditorChange({ editor, html, text }) {
      this.content = html;
    },
  },
  computed: {
    // cateId() {
    //   if (this.ruleForm.goods_cat.length === 3) {
    //     return number(this.ruleForm.goods_cat[2]);
    //   }
    //   return null;
    // },
  },
  watch: {},
};
</script>

<style lang="scss" scoped>
.addBtn {
  margin-top: 10px;
}
</style>
